package com.webflux.webflux02.service;

import com.webflux.webflux02.dao.ProductRepository;
import com.webflux.webflux02.entity.Product;
import com.webflux.webflux02.entity.ProductCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Flux<Product> findByPage(ProductCriteria criteria){
        return productRepository.findByPage(criteria.getType(),criteria.getPage(),criteria.getPageSize());
    }
    public Mono<Product> save(Product product){
        return productRepository.save(product);
    }

    public Mono<Product> findById(Integer id){
        return productRepository.findById(id).switchIfEmpty(Mono.empty());
    }

    public Mono<Void> delete(Integer id){
            return productRepository.findById(id).flatMap(productRepository::delete);
        }

        public Flux<Product> findAll(){
            return productRepository.findAll();
        }

        public Mono<Product> updateById(Product product){

            return productRepository.existsById(product.getId()).flatMap(item ->{
                if(item){
                    return productRepository.save(product);
                }
                return Mono.empty();
        });
    }





}
